<?php
/**
 * 商品类型
 * User: ws
 * Date: 2018/8/7
 * Time: 15:59
 */

namespace app\admin\controller;

class Type extends Init
{
    function _initialize()
    {
        parent::_initialize();
        $this->model = model('goods_type');
    }


    function index(){
        if ($this->request->isAjax()) {
            $list = $this->model->get_list('', '', input('limit'), 2);
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list');
    }

    function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $name = $this->model->where('name',$data['name'])->find();
            if($name){
                return json(array('code'=>0,'msg'=>'添加失败，不能有相同的名称'));
            }
            if(empty($data['type_id'])){
                unset($data['type_id']);
                $rul = $this->model->add($data);
            }else{
                $rul = $this->model->edit($data);
            }
            if ($rul) {
                return json(array('code'=>200,'msg'=>'添加成功'));
            }
            return json(array('code'=>0,'msg'=>'添加失败'));
        }


        if(!empty(input('id'))){
            $list = $this->model->where('type_id', input('id'))->find()->toArray();
            return view('add',['list'=>$list,]);
        }
        $list['type_id'] = '';
        $list['name'] = '';
        return view('add',['list'=>$list]);
    }

    function del(){
        $result = $this->model->destroy(input('type_id'));
        if($result){
            return json(array('code'=>200,'msg'=>'删除成功'));
        }else{
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
    }
}